package com.jp.knowledge.fragment;

import android.animation.LayoutTransition;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.InfoDataDetailActivity;
import com.jp.knowledge.adapter.CommtemAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.HomePageRecyclerView;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by jiayen on 16/9/27.
 */
public class CommNewsFragment extends BaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, ResultSubscriber.OnResultListener {

    protected final int HEAD_LINE_DATA_CODE = 0x00000001;
    protected boolean REFRESH_MODE = true;

    protected View mView;
    protected HomePageRecyclerView listView;
    protected CanRefreshLayout mRefresh;
    private TextView tipText;
    protected LinearLayout emptyDataView;

    protected CommtemAdapter adapter;
    protected String typeId;                    //导航分类id
    protected List<HeadLineData> headLineDatas; //列表数据

    protected String CACHE_DATA_PATH ;          //缓存路径
    protected FileCacheManager cacheManager;
    private UserData userData;

    private Animation tipShowAinma;
    private Animation tipHideAnima;
    private LocalBroadcastManager localBroadcastManager;
    private LocalBroadCast localBroadCast;
    private boolean   readCache=true;
    public void newInstance(String typeId) {
        this.typeId = typeId;
    }

    public String getTypeId() {
        return typeId;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mView = View.inflate(getContext(), R.layout.comm_new_fragment, null);
        init();

        ViewGroup  dataView = (ViewGroup) mView.findViewById(R.id.data_view);
        LayoutTransition transition = new LayoutTransition();
        dataView.setLayoutTransition(transition);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return mView;
    }

    protected void init() {
        cacheManager= new FileCacheManager();
        initCachePath();
        tipText = (TextView) mView.findViewById(R.id.tip);
        mRefresh = (CanRefreshLayout) mView.findViewById(R.id.refresh);
        listView = (HomePageRecyclerView) mView.findViewById(R.id.can_content_view);
        emptyDataView = (LinearLayout) mView.findViewById(R.id.comm_new_fragment_remind_bg);
        if(emptyDataImg > 0)
            ((ImageView)mView.findViewById(R.id.empty_image)).setImageResource(emptyDataImg);
        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);
        headLineDatas = new ArrayList<>();
        userData = application.getUserData();
        initAdapter();
        initAdapterItemClickListener();
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        listView.setHasFixedSize(true);
        listView.setLayoutManager(manager);
        listView.setAdapter(adapter);

        registerBrod();
        if(readCache){
            readCacheData();
        }else {
            autoRefresh(false);
        }

    }

    protected void initCachePath(){
        CACHE_DATA_PATH = getContext().getCacheDir().getPath()+"/head_data_"+typeId+".data";
    }
    protected void initAdapter(){
        adapter = new CommtemAdapter(mContext, headLineDatas);
    }
    protected void initAdapterItemClickListener(){
        adapter.setOnItemListener(new OnItemListerner() {
            @Override
            public void onItemClick(View view, int i) {
                adapter.updateTitleColor(i);
                Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
                intent.putExtra("id", headLineDatas.get(i).getId());
                intent.putExtra("type", headLineDatas.get(i).getType());
                intent.putExtra("linkTitle", headLineDatas.get(i).getTitle());
                try {
                    intent.putExtra("linkIcon", headLineDatas.get(i).getImglist().get(0).getSrc());
                }catch (Exception e){} finally {
                    startActivity(intent);
                }
            }
        });
    }

    /* 注册广播刷新数据（目前是改变字体大小用） */
    private void registerBrod() {
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                receiveBroadCast(context, intent);
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.COMM_CHANGE_SIZE);//改变字体大小
        intentFilter.addAction(LocalBroadCast.HEAD_NAV_CORRECTING);//校正分类
        intentFilter.addAction(LocalBroadCast.DETAIL_SC_BROAD);//收藏
        intentFilter.addAction(LocalBroadCast.LOGIN_SUCCESS_BROD);
        intentFilter.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
        intentFilter.addAction(LocalBroadCast.GET_LOGIN_INFO);
        localBroadcastManager.registerReceiver(localBroadCast,intentFilter);
    }

    protected void receiveBroadCast(Context context, Intent intent){
        String action = intent.getAction();
        if(action == null)
            return;
        if(action.equals(LocalBroadCast.COMM_CHANGE_SIZE)) {
            adapter.changeTextSize();
        }else if(action.equals(LocalBroadCast.HEAD_NAV_CORRECTING)){
            adapter.removeSelectItem(adapter.DEFALUT_POSTION);//默认的当前位置
        } else if(action.equals(LocalBroadCast.DETAIL_SC_BROAD)){
            String id = intent.getStringExtra("id");
            int isCollection = intent.getIntExtra("isCollection", -1);
            if(isCollection < 0 || headLineDatas == null || headLineDatas.size() == 0)
                return;
            for(HeadLineData headLineData : headLineDatas){
                if(!headLineData.getId().equals(id))
                    continue;
                headLineData.setIsFollow(isCollection);
                adapter.updataAdapter(headLineDatas);
                return;
            }
        }  else if(action.equals(LocalBroadCast.LOGIN_SUCCESS_BROD)
                || action.equals(LocalBroadCast.LOGOUT_SUCCESS_BROD)
                || action.equals(LocalBroadCast.GET_LOGIN_INFO)){
            adapter.updataAdapter(headLineDatas);
        }
    }

    /* 更新数据 */
    public void update(){
        readCacheData();
    }

    public void autoRefresh(boolean showRefreshView){
        if (headLineDatas == null || headLineDatas.size() == 0) {
            if(showRefreshView) {
                listView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRefresh.autoRefresh();
                    }
                }, 300);
            } else {
                onRefresh();
            }
        }
    }
    /**
     * 读取缓存数据
     */
    protected void readCacheData() {

        Observable.create(new Observable.OnSubscribe<List<HeadLineData>>() {
            @Override
            public void call(Subscriber<? super List<HeadLineData>> subscriber) {
                Object obj =  cacheManager.readObject(CACHE_DATA_PATH);
                List<HeadLineData> list = null;
                if(obj!=null)
                    list = (List<HeadLineData>) obj;
                subscriber.onNext(list);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
         .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer< List<HeadLineData>>() {
            @Override
            public void onCompleted() {
                autoRefresh(false);
                emptyDataView.setVisibility(listView.getAdapter().getItemCount() > 0 ? View.GONE : View.VISIBLE);
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext( List<HeadLineData> list ) {
                headLineDatas=list;
                adapter.updataAdapter(list);
            }
        });
    }

    @Override
    public void onRefresh() {
        if (headLineDatas == null || headLineDatas.size() == 0)
            getHeadLineData(typeId, 0, System.currentTimeMillis());
        else
            getHeadLineData(typeId, 0, headLineDatas.get(0).getCreatetime());
    }

    @Override
    public void onLoadMore() {
        if(headLineDatas == null || headLineDatas.size() == 0)
            getHeadLineData(typeId, 1, headLineDatas.get(headLineDatas.size() - 1).getCreatetime());
        else
            getHeadLineData(typeId, 1, System.currentTimeMillis());
    }

    /* 获取headline模块列表数据 */
    protected void getHeadLineData(String typeId, int mode, long time) {
        REFRESH_MODE = (mode == 0);
        JsonObject param = new JsonObject();
        param.addProperty("label", typeId);
        param.addProperty("time", time);
        param.addProperty("mode", mode);
        HttpHelper.getInstance(mContext).getHeadLineData(param, HEAD_LINE_DATA_CODE, this);
    }


    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if (REFRESH_MODE) {
            mRefresh.refreshComplete();
            if(refreshListener != null)
                refreshListener.onRefreshFinish(typeId);
        } else {
            mRefresh.loadMoreComplete();
        }
        emptyDataView.setVisibility(listView.getAdapter().getItemCount() > 0 ? View.GONE : View.VISIBLE);
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }

    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else  if (requestType == HEAD_LINE_DATA_CODE) {
            if(headLineDatas == null)
                headLineDatas = new ArrayList<>();
            if(REFRESH_MODE)
                headLineDatas.clear();
            List<HeadLineData> list = data.getList(HeadLineData.class);
            if(list != null && list.size() > 0){
                headLineDatas.addAll(list);
                showTip(list.size());
            }
            adapter.updataAdapter(headLineDatas);
        }
    }

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        saveCacheData();
        super.onDestroy();
    }

    /* 保存数据缓存，最多 20 条 */
    protected void saveCacheData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                headLineDatas =  adapter.getData();
                int size = (headLineDatas==null?0:headLineDatas.size());
                List<HeadLineData> temp = new ArrayList<>();
                if(size>20)
                    for (int i = 0; i <20 ; i++)
                        temp.add(headLineDatas.get(i));
                else
                    temp=headLineDatas;
                final  List<HeadLineData> cacheData = temp;
                cacheManager.wirteObject(cacheData,CACHE_DATA_PATH);
            }
        }).start();
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            tipText.setVisibility(View.GONE);
        }
    };
    /*  显示提示信息 */
    private void showTip(int size) {
        if(!showTipAfterGetData)
            return;
        if(size == 0)
            tipText.setText("暂无新数据");
        else
            tipText.setText("为你更新了" + size + "条新数据");
        tipHideAnima = AnimationUtils.loadAnimation(mContext, R.anim.tip_hide);
        tipShowAinma = AnimationUtils.loadAnimation(mContext, R.anim.tip_show);
        tipText.setAnimation(tipShowAinma);
        tipText.setVisibility(View.VISIBLE);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                handler.sendEmptyMessage(1);
            }
        }, 1500);
    }

    int emptyDataImg = -1;
    public void setEmptyDataViewImage(int mipmap){
        try {
            ((ImageView)mView.findViewById(R.id.empty_image)).setImageResource(mipmap);
        } catch (Exception e){} finally {
            emptyDataImg = mipmap;
        }
    }

//    private boolean showTipAfterGetData = true;
    private boolean showTipAfterGetData = false;
    public void showTipAfterGetData(boolean isShow){
//        showTipAfterGetData = isShow;
        if(!showTipAfterGetData) {
            tipText.setVisibility(View.GONE);
            mRefresh.refreshComplete();
        }
    }
    public void setRefreshEnabled(boolean refreshEnabled){
        mRefresh.setRefreshEnabled(refreshEnabled);
    }
    public void setLoadMoreEnabled(boolean loadMoreEnabled){
        mRefresh.setLoadMoreEnabled(loadMoreEnabled);
    }
    public void scrollToStart(){
        listView.scrollToPosition(0);
    }
    public void setCanFling(boolean canFling){
        listView.setCanFling(canFling);
    }

    private RefreshListener refreshListener;
    public void setRefreshListener(RefreshListener refreshListener){
        this.refreshListener = refreshListener;
    }
    public interface RefreshListener{
        void onRefreshFinish(String typeId);
    }

    public void setReadCache(boolean readCache) {
        this.readCache = readCache;
    }
}
